package org.hu.Filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hu.utils.JwtUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;


//@Component
public class JwtFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");



        if (token != null) {
            try {
                String username = JwtUtil.parseToken(token.replace("Bearer ", ""));
                request.setAttribute("username", username); // 可注入到后续接口中
                chain.doFilter(request, response);
                return;
            } catch (Exception e) {
                ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Token 非法");
                return;
            }
        }

        // 登录、注册接口放行
        String path = req.getRequestURI();
        // 放行静态资源
        if (path.startsWith("/images/")) {
            chain.doFilter(request, response);
            return;
        }
        if (path.equals("/auth/login") || path.equals("/wxlogin") || path.equals("/images/**")) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("未登录");
        }
    }
}

